package com.tfswx.fljdmxyy.utils;

import cn.hutool.json.JSONUtil;
import com.tfswx.fljdmxyy.utils.sm4.DecryptSm4InputStream;
import com.tfswx.fljdmxyy.utils.sm4.EncryptSm4InputStream;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.IOUtils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * str工具
 *
 * @Author 陈文佳
 * @Date 2023/03/24
 */
public class StrUtils {
    private StrUtils() {
    }

    public static String encrypt(String str) {
        if (str == null) {
            return null;
        }
        byte[] bytes = str.getBytes(StandardCharsets.UTF_8);
        try (EncryptSm4InputStream sm4InputStream = new EncryptSm4InputStream(new ByteArrayInputStream(bytes));
             ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
            IOUtils.copy(sm4InputStream, outputStream);
            byte[] bytes1 = Base64.encodeBase64(outputStream.toByteArray());
            return new String(bytes1, StandardCharsets.UTF_8).replace("=", "");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static String decrypt(String str) {
        if (str == null) {
            return null;
        }
        byte[] bytes = Base64.decodeBase64(str);
        try (DecryptSm4InputStream sm4InputStream = new DecryptSm4InputStream(new ByteArrayInputStream(bytes));
             ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
            IOUtils.copy(sm4InputStream, outputStream);
            return new String(outputStream.toByteArray(), StandardCharsets.UTF_8);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static boolean isJSON(String str) {
        boolean result = false;
        try {
            Object obj = JSONUtil.parse(str);
            result = true;
        } catch (Exception e) {
            result = false;
        }
        return result;
    }
}
